from django.shortcuts import render, redirect, reverse
from django.http import JsonResponse
import string
import random
from django.core.mail import send_mail
from .models import CaptchaModel
from django.views.decorators.http import require_http_methods
from .forms import RegisterForm, LoginForm
from django.contrib.auth import get_user_model, login, logout
from django.contrib.auth.models import User

User = get_user_model()


# Create your views here.
@require_http_methods(['GET', 'POST'])
def bloglogin(request):
    if request.method == 'GET':  #GET 请求方法通常用于请求和获取数据或页面，而不修改服务器上的数据
        return render(request, 'login.html')
    else:
        # 在表单提交时，用户输入的数据会被封装在 request.POST 中
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            remember = form.cleaned_data.get('remember')
            user = User.objects.filter(email=email).first()
            if user and user.check_password(password):
                # 登录
                login(request, user)
                user.is_authenticated
                # 判断是否需要记住我
                if not remember:
                    # 如果没有点击记住我,那么设置过期时间为0,浏览器关闭后会过期
                    request.session.set_expiry(0)
                # 如果点击了,那么就什么都不做,使用默认的2周的过期时间
                return redirect('index')
            else:
                print('邮箱或者密码错误')
                # form.add_error('email', '邮箱或者密码错误')
                # return render(request, 'login.html',context={'form': form})
                return redirect(reverse('blogauth:login'))


def loginout(request):
    logout(request)
    return redirect('index')

@require_http_methods(['GET', 'POST'])
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        form = RegisterForm(request.POST)
        #  用于验证表单数据
        if form.is_valid():
            email = form.cleaned_data.get('email')
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            User.objects.create_user(email=email, username=username, password=password)
            return redirect(reverse('blogauth:login'))
        else:
            print(form.errors)
            # 重新跳转到注册页面
            return redirect(reverse('blogauth:register'))
            # return render(request, 'register.html', context={'form': form})


def send_mail_captcha(request):
    # ?email = XXX
    # print("1111111111111")
    email = request.GET.get('email')
    if not email:
        return JsonResponse({"code": 400, "msg": "必须传递邮箱"})
    # 生成验证码（随机生成四位数）
    captcha = "".join(random.sample(string.digits, 4))
    # 把生成的验证码存储到数据库，并且如果这个邮箱的验证码已存在，更新发送，不存在这创建发送
    CaptchaModel.objects.update_or_create(email=email, defaults={"captcha": captcha})
    send_mail("知了博客注册验证码", message=f"你的注册验证码是：{captcha}", recipient_list=[email], from_email=None)
    print(captcha)
    return JsonResponse({"code": 200, "msg": "发送成功"})
